package com.jingbaoduo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingbaoduo.common.BaseContext;
import com.jingbaoduo.common.R;
import com.jingbaoduo.domain.Goods;
import com.jingbaoduo.domain.Orders;
import com.jingbaoduo.domain.OrdersDetail;
import com.jingbaoduo.domain.ShoppingCart;
import com.jingbaoduo.dto.OrdersDto;
import com.jingbaoduo.service.GoodsService;
import com.jingbaoduo.service.OrdersDetailService;
import com.jingbaoduo.service.OrdersService;
import com.jingbaoduo.service.ShoppingCartService;
import com.jingbaoduo.utils.OrderUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrdersDetailService ordersDetailService;

    @Autowired
    private GoodsService goodsService;

    @PostMapping
    public R<Orders> add(@RequestBody OrdersDto ordersDto){

        log.info("添加订单与订单详情表");

        Orders orders = new Orders();
        //将ordersDto中的属性复制到orders中
        BeanUtils.copyProperties(ordersDto,orders);
        //设置用户id
        Long currentId = BaseContext.getCurrentId();
        orders.setUserId(currentId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置订单编号
        orders.setNumber(OrderUtils.getOrderCode(currentId));
        //向数据库中添加订单并返回主键
        ordersService.save(orders);
        log.info("返回的主键:{}",orders.getOrderId());
        Long orderId = orders.getOrderId();


        //通过查询购物车中被选中的id查到对应的商品信息 将订单详情信息封装到订单详情表
        List<Long> shoppingIds = ordersDto.getShoppingIds();
        if (shoppingIds != null){


        for (Long shoppingId : shoppingIds) {
            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getShoppingId,shoppingId);
            ShoppingCart one = shoppingCartService.getOne(queryWrapper);

            OrdersDetail ordersDetail = new OrdersDetail();
            ordersDetail.setNumber(one.getNumber());
            ordersDetail.setGoodsId(one.getGoodsId());
            ordersDetail.setOrderId(orderId);
            //计算总价
            ordersDetail.setAmount(one.getAccount().multiply(BigDecimal.valueOf(one.getNumber())));
            ordersDetail.setImage(one.getImage());
            ordersDetail.setGoodsName(one.getShoppingName());
            ordersDetail.setUserId(currentId);
            ordersDetail.setCreateTime(LocalDateTime.now());
            boolean flag = ordersDetailService.save(ordersDetail);

            if (flag){
                //若订单详情保存成功则删除购物车选中的数据
                shoppingCartService.removeById(shoppingId);
            }
        }
        }else {
            LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Goods::getGoodsId,ordersDto.getGoodsId());
            Goods one = goodsService.getOne(queryWrapper);

            OrdersDetail ordersDetail = new OrdersDetail();
            ordersDetail.setNumber(ordersDto.getNum());
            ordersDetail.setGoodsId(one.getGoodsId());
            ordersDetail.setOrderId(orderId);
            //计算总价
            ordersDetail.setAmount(one.getPrice().multiply(BigDecimal.valueOf(ordersDto.getNum())));
            ordersDetail.setImage(one.getImage());
            ordersDetail.setGoodsName(one.getGoodsName());
            ordersDetail.setUserId(currentId);
            ordersDetail.setCreateTime(LocalDateTime.now());
            ordersDetailService.save(ordersDetail);
        }

        return R.success(orders);
    }

    @GetMapping("/recentOrders")
    public R<List<OrdersDetail>> recentOrders(){
        LambdaQueryWrapper<OrdersDetail> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(OrdersDetail::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByDesc(OrdersDetail::getCreateTime);
        queryWrapper.last("limit 5");

        List<OrdersDetail> list = ordersDetailService.list(queryWrapper);

        return R.success(list);
    }

    @DeleteMapping("/{orderId}")
    public R<String> deleteOrder(@PathVariable Long orderId){
        LambdaQueryWrapper<OrdersDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrdersDetail::getOrderId,orderId);
        boolean flag = ordersDetailService.remove(queryWrapper);
        if (flag){
            LambdaQueryWrapper<Orders> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Orders::getOrderId,orderId);
            ordersService.remove(queryWrapper1);
        }

        return R.success("删除成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Integer status){
        Page<OrdersDto> pageInfo = new Page<>(page, pageSize);

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        queryWrapper.eq(!Objects.isNull(status),Orders::getStatus,status);
        queryWrapper.orderByDesc(Orders::getOrderTime).orderByDesc(Orders::getCheckoutTime);;


        ordersService.page(ordersPage, queryWrapper);

        List<OrdersDto> ordersDtoList = ordersPage.getRecords().stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getOrderId();

            LambdaQueryWrapper<OrdersDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrdersDetail::getOrderId, orderId);

            List<OrdersDetail> list = ordersDetailService.list(queryWrapper1);
            ordersDto.setOrdersDetailList(list);

            return ordersDto;
        }).collect(Collectors.toList());

        //将ordersPage中的属性复制到pageInfo中
        BeanUtils.copyProperties(ordersPage, pageInfo);
        pageInfo.setRecords(ordersDtoList);
        return R.success(pageInfo);
    }
}
